package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 注入mapper层
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 调用微信接口服务，获取当前微信用户的openid
     *
     * @param code
     * @return
     */

    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /**
     * 微信登入
     *
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        String openid = getOpenid(dto.getCode());
        // 判断openid是否为空，如果为空表示登入失败，那么就抛出异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前用户是否为新用户
        User user = new User();
        user.setOpenid(openid);
        user = userMapper.login(user);
        if (user == null) {
            // 如果为新用户那么就自动注册，往数据库中存入数据
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.add(user);
        }
        return user;
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1.创建日期列表集合
        List<LocalDate> dateList = new ArrayList<>();
        // 用循环判断起始日期是否在结束日期之前
        while (!begin.isAfter(end)) {
            // 起始日期不在结束日期之后,那么，就把这个日期时间存入到集合中
            dateList.add(begin);
            // 然后起始日期加一天
            begin = begin.plusDays(1);
        }
        // 2.创建新增用户表集合
        List<Integer> newUserList = new ArrayList<>();
        // 3.创建总用户量列表集合
        List<Integer> totalUserList = new ArrayList<>();
        // 4.遍历日期集合，用于条件查找用户数据
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //  创建一个map集合用来存储数据
            Map<String, Object> map = new HashMap<>();
            map.put("endTime", endTime);
            // 查询endTime之前的用户
            Integer totalUser = userMapper.userStatistics(map);
            //  查询在这一区间内的新增的用户
            map.put("beginTime", beginTime);
            Integer newUser = userMapper.userStatistics(map);
            // 存入到新增用户表集合
            newUserList.add(newUser);
            // 存入到总用户量列表集合
            totalUserList.add(totalUser);
        }
        // 5.把这些集合数据转换成字符串返回给前端
        return new UserReportVO(StringUtils.join(dateList, ","),
                StringUtils.join(totalUserList, ","),
                StringUtils.join(newUserList, ",")
        );
    }
}
